<template>
  <el-dialog :visible.sync="warningVisible" @close="destroyElement"
             :width="width"
             :show-close="showClose"
             :close-on-click-modal="showClose"
             :close-on-press-escape="showClose"
             class="credit-up"
  >
    <div class="credit-up__status-title" slot="title">
      配置上分金额
    </div>
    <!--<dialog-subtitle>-->
    <!--<el-warning align="center">可使用上分额度为{{fetchData.leftAmount | currency}}元</el-warning>-->
    <!--</dialog-subtitle>-->
    <el-form class="main-container-main__form" :model="form" :rules="rules" ref="form" :disabled="loading"
             @submit.native.prevent="submit"
             label-position="top"
    >
      <el-form-item class="main-container-main__item" prop="username">
        <div class="credit-up__user-info">
          <div class="credit-up__user-line"></div>
          <svg-icon icon-class="user" class="credit-up__user-icon"></svg-icon>
          <!--<span class="credit-up__user-name">{{info.username}}</span><span class="credit-up__user-date" v-if="info.register_date">注册时间：{{info.register_date | toTime}}</span>-->
          <span class="credit-up__user-name">{{info.username}}</span><span class="credit-up__user-date" v-if="info.timestamp">注册时间：{{info.timestamp | toTime}}</span>
        </div>
      </el-form-item>
      <el-form-item class="main-container-main__item" prop="amount" label="上分额度调整为：">
        <el-input class="main-container-main__input" v-model.number="form.amount" placeholder="请输入金额"
                  auto-complete="off">
          <template slot="prepend">
            <svg-icon icon-class="withdraw"></svg-icon>
          </template>
        </el-input>
      </el-form-item>
      <dialog-subtitle>
        <el-warning>可配置额度范围：（{{fetchLevelData.amount - fetchLevelData.validAllocateAmount | currency}} - {{fetchLevelData.amount + fetchData.validAllocateAmount | currency}}）</el-warning>
        <!--<el-warning>可配置额度范围：（{{fetchLevelData.payOutAmount | currency}} - {{fetchData.validAllocateAmount | currency}}）</el-warning>-->
      </dialog-subtitle>
      <el-form-item vertical-fill>
        <el-button
          @click="close"
        >取消
        </el-button>
        <el-button
          type="primary"
          native-type="submit"
        >确定
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script type="text/jsx">
  import factory from '@/mixins/factory';
  import form from '@/mixins/form';

  import {
    proxyWithdrawInfoApi as getApi,
    secondLevelApi as getLevelApi,
    withdrawSubmitApi as saveApi
  } from "@/services/api/low-level";

  export default {
    name: "credit-up-agent",

    mixins: [form],

    data() {
      const checkAmount = (rule, value, callback) => {
        if (value > this.fetchData.validAllocateAmount + this.fetchLevelData.amount) {
          callback(new Error(`超出上分额度上限`));
        }else if (value < this.fetchLevelData.amount - this.fetchLevelData.validAllocateAmount) {
          callback(new Error(`低于上分额度下限`));
        }else {
          callback();
        }
      };

      return {
        warningVisible: true,
        info: {},
        width: consts.DIALOG_SIZE_NORMAL,
        showClose: true,
        closed: false,
        form: {
          targetUserId: undefined,
          amount: undefined,
        },
        fetchData: {},
        fetchLevelData: {},
        formError: '',
        callback: _.noop,
        rules: {
          amount: [
            ...factory.getRule('money'),
            {validator: checkAmount}
          ]
        },
        showTimeHtml: '',
      }
    },

    computed: {
      ...mapState({
        user: state => state.user,
      }),
    },

    watch: {
      closed(newVal) {
        if (newVal) {
          this.warningVisible = false;
        }
      }
    },

    methods: {
      showTime() {
        if (this.info.timestamp){
          this.showTimeHtml = `<div class="credit-up-tip__cell"><div class="credit-up-tip__left">注册时间</div><div class="credit-up-tip__right">${_.toTime(this.info.timestamp)}</div></div>`;
        }else {
          this.showTimeHtml = '';
        }
      },
      close() {
        this.closed = true;
        if (typeof this.onClose === 'function') {
          this.onClose(this);
        }
      },
      submit() {
        this.showTime();
        this.$refs.form.validate().then(() => {
          this.$confirm(`<div class="credit-up-tip"><div class="credit-up-tip__integral">¥${_.currency(this.form.amount)}</div>
                          <div class="credit-up-tip__cell"><div class="credit-up-tip__left">代理账户</div><div class="credit-up-tip__right">${this.info.username}</div></div>
                          `+this.showTimeHtml+`</div>`, '确认配置上分金额', {
            confirmButtonText: '确认上分',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            // type: 'warning',
            center: true
          }).then(() => {
            this.doSave({action: 'saveForm', form: 'form'});
          }).catch(() => {
          });
        }).catch(() => {
          return false;
        });
      },
      destroyElement() {
        this.$destroy(true);
        this.$el.parentNode.removeChild(this.$el);
      },
    },

    mounted() {
      this.form.targetUserId = this.info.id;
      this.bindGet(getApi, 'fetchData');

      this.bindSave(saveApi, 'saveForm', 'form', {
        beforeSend: (data) => {

          this.formError = '';
          return data;
        },
        successMessage: '',
        afterSuccess: () => {
          this.$store.dispatch(types.GET_CREDIT_STATUS);

          const vm = this.$messageTip({
            title: '配置上分金额成功',
            message: <div class="credit-up-tip">
              <div class="credit-up-tip__cell"><div class="credit-up-tip__left">代理账户</div><div class="credit-up-tip__right">{this.info.username}</div></div>
              <div class="credit-up-tip__cell"><div class="credit-up-tip__left">上分金额</div><div class="credit-up-tip__right">{_.currency(this.form.amount)}</div></div>
            </div>,
            // type: 'success',
            goTo: <el-button type="primary" block onClick={() => {
              // this.callback('success');
              vm.close();
              this.close();
            }}>知道了</el-button>
          });
        },
        afterFail: ([result, data]) => {
          this.formError = data.message;
          this.$message.error({
            message: data.message,
          });
          // this.$notify({
          //   title: this.formError,
          //   type: 'error',
          //   duration: 2000
          // });
        }
      });
      this.bindGet(getLevelApi, 'fetchLevelData', {
        sendingData: {
          userId: this.info.id
        }
      });

      this.getAll();
    }
  };
</script>

<style lang="scss" scoped>
  @include b(credit-up) {
    @include e(status-title) {
      height: 60px;
      font-size: 28px;
      font-weight: bold;
      line-height: 60px;
    }
    @include e(user-info) {
      width: 100%;
      height: 0.5rem;
      line-height: 0.5rem;
      position: relative;
      border: 1px solid $--border-color-base-1;
      border-radius: 8px;
      overflow: hidden;
      display: flex;
      @include e(user-line) {
        width: 6px;
        height: 0.5rem;
        background: $--color-primary;
      }
      @include e(user-icon) {
        fill: $--color-primary;
        margin: 0 10px;
        height: 0.5rem;
      }
      @include e(user-name) {
        font-size: 0.18rem;
      }
      @include e(user-date) {
        position: absolute;
        right: 5px;
      }
    }
  }

</style>
<style lang="scss">
  @include b(credit-up-tip) {
    @include e(integral) {
      color: #333333;
      font-weight: bold;
      margin-bottom: 0;
      font-size: 0.28rem;
      line-height: 1;
      padding: 0.1rem 0 0.3rem 0;
    }
    @include e(cell) {
      width: 100%;
      height: 0.4rem;
      line-height: 0.4rem;
      border-bottom: 1px solid $--border-color-base-1;
      color: #333333;
      font-size: 14px;
    }
    @include e(left) {
      float: left;
      display: inline-block;
    }
    @include e(right) {
      float: right;
      display: inline-block;
    }
  }
</style>
